package com.spzx.order.receiver;

import com.rabbitmq.client.Channel;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.order.service.IOrderInfoService;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

/**
 * Package: com.spzx.order.receiver
 *
 * @Description:
 * @Author xiongkunYang
 * @Create 2025/6/3 9:19
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderReceiver {

    private final IOrderInfoService orderInfoService;

    /**
     * 监听订单支付成功消息；更新订单状态
     *
     * @param orderNo  订单编号
     * @param message  消息
     * @param channel  信道
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            exchange = @Exchange(value = MqConst.EXCHANGE_PAYMENT_PAY, durable = "true"),
            value = @Queue(value = MqConst.QUEUE_PAYMENT_PAY, durable = "true"),
            key = MqConst.ROUTING_PAYMENT_PAY
    ))
    public void testReceive(String orderNo, Message message, Channel channel) {

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("修改订单状态......" + orderNo);
            orderInfoService.processPaySuccess(orderNo);
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("修改订单状态失败......{}", orderNo, e);
            channel.basicNack(deliveryTag, false, false);
        }
    }
}